using System;
using ch.ethz.ssh2.channel;
using Org.BouncyCastle.Security;
namespace ch.ethz.ssh2
{
	
	/// <summary> A <code>Session</code> is a remote execution of a program. "Program" means
	/// in this context either a shell, an application or a system command. The
	/// program may or may not have a tty. Only one single program can be started on
	/// a session. However, multiple sessions can be active simultaneously.
	/// 
	/// </summary>
	/// <author>  Christian Plattner
	/// </author>
	/// <version>  2.50, 03/15/10
	/// </version>
	public class Session
	{
		virtual public System.IO.Stream Stdout
		{
			get
			{
				return cn.StdoutStream;
			}
			
		}
		virtual public System.IO.Stream Stderr
		{
			get
			{
				return cn.StderrStream;
			}
			
		}
		virtual public System.IO.Stream Stdin
		{
			get
			{
				return cn.StdinStream;
			}
			
		}
		/// <summary> Get the exit code/status from the remote command - if available. Be
		/// careful - not all server implementations return this value. It is
		/// generally a good idea to call this method only when all data from the
		/// remote side has been consumed (see also the <code<WaitForCondition</code> method).
		/// 
		/// </summary>
		/// <returns> An <code>Integer</code> holding the exit code, or
		/// <code>null</code> if no exit code is (yet) available.
		/// </returns>
		virtual public System.Int32 ExitStatus
		{
			get
			{
				return cn.ExitStatus;
			}
			
		}
		/// <summary> Get the name of the signal by which the process on the remote side was
		/// stopped - if available and applicable. Be careful - not all server
		/// implementations return this value.
		/// 
		/// </summary>
		/// <returns> An <code>String</code> holding the name of the signal, or
		/// <code>null</code> if the process exited normally or is still
		/// running (or if the server forgot to send this information).
		/// </returns>
		virtual public System.String ExitSignal
		{
			get
			{
				return cn.ExitSignal;
			}
			
		}
		internal ChannelManager cm;
		internal Channel cn;
		
		internal bool flag_pty_requested = false;
		internal bool flag_x11_requested = false;
		internal bool flag_execution_started = false;
		internal bool flag_closed = false;
		
		internal System.String x11FakeCookie = null;
		
		internal SecureRandom rnd;
		
		internal Session(ChannelManager cm, SecureRandom rnd)
		{
			this.cm = cm;
			this.cn = cm.openSessionChannel();
			this.rnd = rnd;
		}
		
		/// <summary> Basically just a wrapper for lazy people - identical to calling
		/// <code>requestPTY("dumb", 0, 0, 0, 0, null)</code>.
		/// 
		/// </summary>
		/// <throws>  IOException </throws>
		public virtual void  requestDumbPTY()
		{
			requestPTY("dumb", 0, 0, 0, 0, null);
		}
		
		/// <summary> Basically just another wrapper for lazy people - identical to calling
		/// <code>requestPTY(term, 0, 0, 0, 0, null)</code>.
		/// 
		/// </summary>
		/// <throws>  IOException </throws>
		public virtual void  requestPTY(System.String term)
		{
			requestPTY(term, 0, 0, 0, 0, null);
		}
		
		/// <summary> Allocate a pseudo-terminal for this session.
		/// <p>
		/// This method may only be called before a program or shell is started in
		/// this session.
		/// <p>
		/// Different aspects can be specified:
		/// <p>
		/// <ul>
		/// <li>The TERM environment variable value (e.g., vt100)</li>
		/// <li>The terminal's dimensions.</li>
		/// <li>The encoded terminal modes.</li>
		/// </ul>
		/// Zero dimension parameters are ignored. The character/row dimensions
		/// override the pixel dimensions (when nonzero). Pixel dimensions refer to
		/// the drawable area of the window. The dimension parameters are only
		/// informational. The encoding of terminal modes (parameter
		/// <code>terminal_modes</code>) is described in RFC4254.
		/// 
		/// </summary>
		/// <param name="term">The TERM environment variable value (e.g., vt100)
		/// </param>
		/// <param name="term_width_characters">terminal width, characters (e.g., 80)
		/// </param>
		/// <param name="term_height_characters">terminal height, rows (e.g., 24)
		/// </param>
		/// <param name="term_width_pixels">terminal width, pixels (e.g., 640)
		/// </param>
		/// <param name="term_height_pixels">terminal height, pixels (e.g., 480)
		/// </param>
		/// <param name="terminal_modes">encoded terminal modes (may be <code>null</code>)
		/// </param>
		/// <throws>  IOException </throws>
		public virtual void  requestPTY(System.String term, int term_width_characters, int term_height_characters, int term_width_pixels, int term_height_pixels, byte[] terminal_modes)
		{
			if (term == null)
				throw new System.ArgumentException("TERM cannot be null.");
			
			if ((terminal_modes != null) && (terminal_modes.Length > 0))
			{
				if (terminal_modes[terminal_modes.Length - 1] != 0)
					throw new System.IO.IOException("Illegal terminal modes description, does not end in zero byte");
			}
			else
				terminal_modes = new byte[]{0};
			
			lock (this)
			{
				/* The following is just a nicer error, we would catch it anyway later in the channel code */
				if (flag_closed)
					throw new System.IO.IOException("This session is closed.");
				
				if (flag_pty_requested)
					throw new System.IO.IOException("A PTY was already requested.");
				
				if (flag_execution_started)
					throw new System.IO.IOException("Cannot request PTY at this stage anymore, a remote execution has already started.");
				
				flag_pty_requested = true;
			}
			
			cm.requestPTY(cn, term, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels, terminal_modes);
		}
		
		/// <summary> Request X11 forwarding for the current session.
		/// <p>
		/// You have to supply the name and port of your X-server.
		/// <p>
		/// This method may only be called before a program or shell is started in
		/// this session.
		/// 
		/// </summary>
		/// <param name="hostname">the hostname of the real (target) X11 server (e.g., 127.0.0.1)
		/// </param>
		/// <param name="port">the port of the real (target) X11 server (e.g., 6010)
		/// </param>
		/// <param name="cookie">if non-null, then present this cookie to the real X11 server
		/// </param>
		/// <param name="singleConnection">if true, then the server is instructed to only forward one single
		/// connection, no more connections shall be forwarded after first, or after the session
		/// channel has been closed
		/// </param>
		/// <throws>  IOException </throws>
		public virtual void  requestX11Forwarding(System.String hostname, int port, byte[] cookie, bool singleConnection)
		{
			if (hostname == null)
				throw new System.ArgumentException("hostname argument may not be null");
			
			lock (this)
			{
				/* The following is just a nicer error, we would catch it anyway later in the channel code */
				if (flag_closed)
					throw new System.IO.IOException("This session is closed.");
				
				if (flag_x11_requested)
					throw new System.IO.IOException("X11 forwarding was already requested.");
				
				if (flag_execution_started)
					throw new System.IO.IOException("Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
				
				flag_x11_requested = true;
			}
			
			/* X11ServerData - used to store data about the target X11 server */
			
			X11ServerData x11data = new X11ServerData();
			
			x11data.hostname = hostname;
			x11data.port = port;
			x11data.x11_magic_cookie = cookie; /* if non-null, then present this cookie to the real X11 server */
			
			/* Generate fake cookie - this one is used between remote clients and the ganymed proxy */
			
			byte[] fakeCookie = new byte[16];
			System.String hexEncodedFakeCookie;
			
			/* Make sure that this fake cookie is unique for this connection */
			
			while (true)
			{
				rnd.NextBytes(fakeCookie);
				
				/* Generate also hex representation of fake cookie */
				
				System.Text.StringBuilder tmp = new System.Text.StringBuilder(32);
				for (int i = 0; i < fakeCookie.Length; i++)
				{
					System.String digit2 = System.Convert.ToString(fakeCookie[i] & 0xff, 16);
					tmp.Append((digit2.Length == 2)?digit2:"0" + digit2);
				}
				hexEncodedFakeCookie = tmp.ToString();
				
				/* Well, yes, chances are low, but we want to be on the safe side */
				
				if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
					break;
			}
			
			/* Ask for X11 forwarding */
			
			cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
			
			/* OK, that went fine, get ready to accept X11 connections... */
			/* ... but only if the user has not called close() in the meantime =) */
			
			lock (this)
			{
				if (flag_closed == false)
				{
					this.x11FakeCookie = hexEncodedFakeCookie;
					cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
				}
			}
			
			/* Now it is safe to start remote X11 programs */
		}
		
		/// <summary> Execute a command on the remote machine.
		/// 
		/// </summary>
		/// <param name="cmd">The command to execute on the remote host.
		/// </param>
		/// <throws>  IOException </throws>
		public virtual void  execCommand(System.String cmd)
		{
			if (cmd == null)
				throw new System.ArgumentException("cmd argument may not be null");
			
			lock (this)
			{
				/* The following is just a nicer error, we would catch it anyway later in the channel code */
				if (flag_closed)
					throw new System.IO.IOException("This session is closed.");
				
				if (flag_execution_started)
					throw new System.IO.IOException("A remote execution has already started.");
				
				flag_execution_started = true;
			}
			
			cm.requestExecCommand(cn, cmd);
		}
		
		/// <summary> Start a shell on the remote machine.
		/// 
		/// </summary>
		/// <throws>  IOException </throws>
		public virtual void  startShell()
		{
			lock (this)
			{
				/* The following is just a nicer error, we would catch it anyway later in the channel code */
				if (flag_closed)
					throw new System.IO.IOException("This session is closed.");
				
				if (flag_execution_started)
					throw new System.IO.IOException("A remote execution has already started.");
				
				flag_execution_started = true;
			}
			
			cm.requestShell(cn);
		}
		
		/// <summary> Start a subsystem on the remote machine.
		/// Unless you know what you are doing, you will never need this.
		/// 
		/// </summary>
		/// <param name="name">the name of the subsystem.
		/// </param>
		/// <throws>  IOException </throws>
		public virtual void  startSubSystem(System.String name)
		{
			if (name == null)
				throw new System.ArgumentException("name argument may not be null");
			
			lock (this)
			{
				/* The following is just a nicer error, we would catch it anyway later in the channel code */
				if (flag_closed)
					throw new System.IO.IOException("This session is closed.");
				
				if (flag_execution_started)
					throw new System.IO.IOException("A remote execution has already started.");
				
				flag_execution_started = true;
			}
			
			cm.requestSubSystem(cn, name);
		}
		
		/// <summary> This method blocks until there is more data available on either the
		/// stdout or stderr InputStream of this <code>Session</code>. Very useful
		/// if you do not want to use two parallel threads for reading from the two
		/// InputStreams. One can also specify a timeout. NOTE: do NOT call this
		/// method if you use concurrent threads that operate on either of the two
		/// InputStreams of this <code>Session</code> (otherwise this method may
		/// block, even though more data is available).
		/// 
		/// </summary>
		/// <param name="timeout">The (non-negative) timeout in <code>ms</code>. <code>0</code> means no
		/// timeout, the call may block forever.
		/// </param>
		/// <returns>
		/// <ul>
		/// <li><code>0</code> if no more data will arrive.</li>
		/// <li><code>1</code> if more data is available.</li>
		/// <li><code>-1</code> if a timeout occurred.</li>
		/// </ul>
		/// 
		/// </returns>
		/// <throws>     IOException </throws>
		/// <deprecated> This method has been replaced with a much more powerful wait-for-condition
		/// interface and therefore acts only as a wrapper.
		/// 
		/// </deprecated>
		public virtual int waitUntilDataAvailable(long timeout)
		{
			if (timeout < 0)
				throw new System.ArgumentException("timeout must not be negative!");
			
			int conditions = cm.waitForCondition(cn, timeout, ch.ethz.ssh2.ChannelCondition_Fields.STDOUT_DATA | ch.ethz.ssh2.ChannelCondition_Fields.STDERR_DATA | ch.ethz.ssh2.ChannelCondition_Fields.EOF);
			
			if ((conditions & ch.ethz.ssh2.ChannelCondition_Fields.TIMEOUT) != 0)
				return - 1;
			
			if ((conditions & (ch.ethz.ssh2.ChannelCondition_Fields.STDOUT_DATA | ch.ethz.ssh2.ChannelCondition_Fields.STDERR_DATA)) != 0)
				return 1;
			
			/* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
			
			if ((conditions & ch.ethz.ssh2.ChannelCondition_Fields.EOF) != 0)
				return 0;
			
			throw new System.SystemException("Unexpected condition result (" + conditions + ")");
		}
		
		/// <summary> This method blocks until certain conditions hold true on the underlying SSH-2 channel.
		/// <p>
		/// This method returns as soon as one of the following happens:
		/// <ul>
		/// <li>at least of the specified conditions (see {@link ChannelCondition}) holds true</li>
		/// <li>timeout > 0 and a timeout occured (TIMEOUT will be set in result conditions)</a> 
		/// <li>the underlying channel was closed (CLOSED will be set in result conditions)</a>
		/// </ul>
		/// <p>
		/// In any case, the result value contains ALL current conditions, which may be more
		/// than the specified condition set (i.e., never use the "==" operator to test for conditions
		/// in the bitmask, see also comments in {@link ChannelCondition}). 
		/// <p>
		/// Note: do NOT call this method if you want to wait for STDOUT_DATA or STDERR_DATA and
		/// there are concurrent threads (e.g., StreamGobblers) that operate on either of the two
		/// InputStreams of this <code>Session</code> (otherwise this method may
		/// block, even though more data is available in the StreamGobblers).
		/// 
		/// </summary>
		/// <param name="condition_set">a bitmask based on {@link ChannelCondition} values
		/// </param>
		/// <param name="timeout">non-negative timeout in ms, <code>0</code> means no timeout
		/// </param>
		/// <returns> all bitmask specifying all current conditions that are true
		/// </returns>
		
		public virtual int waitForCondition(int condition_set, long timeout)
		{
			if (timeout < 0)
				throw new System.ArgumentException("timeout must be non-negative!");
			
			return cm.waitForCondition(cn, timeout, condition_set);
		}
		
		/// <summary> Close this session. NEVER forget to call this method to free up resources -
		/// even if you got an exception from one of the other methods (or when
		/// getting an Exception on the Input- or OutputStreams). Sometimes these other
		/// methods may throw an exception, saying that the underlying channel is
		/// closed (this can happen, e.g., if the other server sent a close message.)
		/// However, as long as you have not called the <code>close()</code>
		/// method, you may be wasting (local) resources.
		/// 
		/// </summary>
		public virtual void  close()
		{
			lock (this)
			{
				if (flag_closed)
					return ;
				
				flag_closed = true;
				
				if (x11FakeCookie != null)
					cm.unRegisterX11Cookie(x11FakeCookie, true);
				
				try
				{
					cm.closeChannel(cn, "Closed due to user request", true);
				}
				catch (System.IO.IOException ignored)
				{
				}
			}
		}
	}
}